package com.hzit.auth.service;

import com.hzit.auth.entity.LoginUser;
import com.hzit.common.util.R;
import com.hzit.common.util.User;
import com.hzit.auth.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 类名：
 * 作者：WF
 * 功能：进行用户认证功能
 */
@Component("userDetailsService")
public class HzitUserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private UserClient userClient;
	//1. 查询用户是否存在
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1.1 根据用户名查询用户
		R<User> r = userClient.findUserByUsername(username);
		User user = r.getData();
		//1.2 如果用户不存在，就抛出异常
		if(Objects.isNull(user)){
			throw new UsernameNotFoundException("用户名或密码不存在！");
		}
		//1.3  当前登录用户的权限串列表
		R<List<String>> data = userClient.findPermissionsByUsername(username);
		List<String> permissions = data.getData();
		return new LoginUser(username,user.getPassword(),permissions);
	}
}
